// JavaScript Document
window.onload = function() {
	//CheckAll();
	//GetSettleInfo();
}

function GoodsCheck(obj)
{
	var checkId = $(obj).attr('name');
	var checkboxs = $('input[type="checkbox"]');
	
	if ($("#" + checkId).is(':checked'))
	{
		$("#" + checkId).removeAttr('checked');
		$(obj).removeAttr('class');
	}
	else
	{
		$("#" + checkId).prop('checked', 'checked');
		$(obj).prop('class', 'checked');		
	}
	var c=0;//定义一个计数变量
	var checkIdLength = checkboxs.length-1;
    for(var j=0;j<checkIdLength;j++){//遍历items
         if(checkboxs[j].checked==true){//如果状态为选中，count+1
             c++;
         }
    }
    //console.log(c);
    if(c==checkIdLength){//如果被选中的个数等于items的长度
    	$("#check_all").prop('checked', 'checked');
		$('label[name="check_all"]').prop('class', 'checked');
    }else{
    	$("#check_all").removeAttr('checked');
		$('label[name="check_all"]').removeAttr('class');
    }

		
	GetSettleInfo();
}

function CheckAll()
{
	var checkboxs = $('input[type="checkbox"]');
	
	var isChecked = $("#check_all").is(':checked')

	for (var i=0; i<checkboxs.length; i++)
	{
		var name = $(checkboxs[i]).attr('id');
		
/*		if (isChecked)
		{
			$(checkboxs[i]).removeAttr('checked');
			$('label[name="' + name + '"]').removeAttr('class');
		}
		else
		{
			$(checkboxs[i]).attr('checked', 'checked');
			$('label[name="' + name + '"]').attr('class', 'checked');
		}*/
		
		if (isChecked)
		{
			$(checkboxs[i]).removeAttr('checked');
			$('label[name="' + name + '"]').removeAttr('class');
		}
		else
		{
			$(checkboxs[i]).prop('checked', 'checked');
			$('label[name="' + name + '"]').prop('class', 'checked');
		}		
	}
	
	GetSettleInfo();
}

function InitDelete()
{
	 // 设定每一行的宽度=屏幕宽度+按钮宽度
    $(".line-scroll-wrapper").width($(".line-wrapper").width() + $(".line-btn-delete").width());
    $(".cart_item").width($(".line-wrapper").width());
	
    // 获取所有行，对每一行设置监听
    var lines = $(".cart_item");
    var len = lines.length; 
    var lastX, lastXForMobile;
    // 用于记录被按下的对象
    var pressedObj;  // 当前左滑的对象
    var lastLeftObj; // 上一个左滑的对象
    // 用于记录按下的点
    var start;
    // 网页在移动端运行时的监听
    for (var i = 0; i < len; ++i) {
        lines[i].addEventListener('touchstart', function(e){
            lastXForMobile = e.changedTouches[0].pageX;
            pressedObj = this; // 记录被按下的对象 
            // 记录开始按下时的点
            var touches = event.touches[0];
            start = { 
                x: touches.pageX, // 横坐标
                y: touches.pageY  // 纵坐标
            };
        });
        lines[i].addEventListener('touchmove',function(e){
            // 计算划动过程中x和y的变化量
            var touches = event.touches[0];
            delta = {
                x: touches.pageX - start.x,
                y: touches.pageY - start.y
            };
            // 横向位移大于纵向位移，阻止纵向滚动
            if (Math.abs(delta.x) > Math.abs(delta.y)) {
                event.preventDefault();
            }
        });
        lines[i].addEventListener('touchend', function(e){
            if (lastLeftObj && pressedObj != lastLeftObj) { // 点击除当前左滑对象之外的任意其他位置
                $(lastLeftObj).animate({marginLeft:"0"}, 100); // 右滑
                lastLeftObj = null; // 清空上一个左滑的对象
            }
            var diffX = e.changedTouches[0].pageX - lastXForMobile;
            if (diffX < -50) {
                $(pressedObj).animate({marginLeft:"-100px"}, 100); // 左滑
                lastLeftObj && lastLeftObj != pressedObj && 
                    $(lastLeftObj).animate({marginLeft:"0"}, 100); // 已经左滑状态的按钮右滑
                lastLeftObj = pressedObj; // 记录上一个左滑的对象
            } else if (diffX > 50) {
              if (pressedObj == lastLeftObj) {
                $(pressedObj).animate({marginLeft:"0"}, 100); // 右滑
                lastLeftObj = null; // 清空上一个左滑的对象
              }
            }
        });
    }
    // 网页在PC浏览器中运行时的监听
    /*for (var i = 0; i < len; ++i) {
        $(lines[i]).bind('mousedown', function(e){
            lastX = e.clientX;
            pressedObj = this; // 记录被按下的对象
        });
        $(lines[i]).bind('mouseup', function(e){
            if (lastLeftObj && pressedObj != lastLeftObj) { // 点击除当前左滑对象之外的任意其他位置
                $(lastLeftObj).animate({marginLeft:"0"}, 500); // 右滑
                lastLeftObj = null; // 清空上一个左滑的对象
            }
            var diffX = e.clientX - lastX;
            if (diffX < -150) {
                $(pressedObj).animate({marginLeft:"-100px"}, 500); // 左滑
                lastLeftObj && lastLeftObj != pressedObj && 
                    $(lastLeftObj).animate({marginLeft:"0"}, 500); // 已经左滑状态的按钮右滑
                lastLeftObj = pressedObj; // 记录上一个左滑的对象
            } else if (diffX > 150) {
              if (pressedObj == lastLeftObj) {
                $(pressedObj).animate({marginLeft:"0"}, 500); // 右滑
                lastLeftObj = null; // 清空上一个左滑的对象
              }
            }
        });
    }*/
}

function DisplayCartData(data, cartInfo)
{
	//console.log(data);
	var _html = '';
	var template = 
			'<div class="line-wrapper">' +
                '<div class="line-scroll-wrapper">' +
    				'<div class="cart_item">' +
                        '<input type="checkbox" id="{0}" /><label onclick="GoodsCheck(this);" name="{0}"></label>' +
                        '<img src="{1}">' +
                        '<div class="cart_text">' +
                            '<a class="goods_name">{2}</a>' +
                            '<a class="goods_price">￥ <strong>{3}</strong></a>' +
                            '<a class="goods_count_label">购买数量</a>' +
                        '</div>' +
                        '<div class="goods_count">' +
                        	'<input class="goods_count_input" value="{4}" _max="{5}"/>' +
                        '</div>' +
                    '</div>' +
                    '<div class="line-btn-delete"><button onclick="DeleteFromCart(this, \'{0}\')">删除</button></div>' +
                '</div>' +
            '</div>';
	
	var _cart = cartInfo;
	var count = 0;
	
	for (var i=0; i<data.length; i++)
	{		
		for (var j=0; j<_cart.length; j++)
		{
			if (_cart[j].commodityId == data[i].commodityId)
			{
				count = _cart[j].Count;
				
				_cart.splice(j, 1);
				
				break;
			}
		}
		
		_html += template.format(data[i].commodityId,data[i].photo, data[i].names, data[i].price.toFixed(2), count, data[i].number);
	}
	
	$('#cart_detail').html(_html);
	
	InitDelete();
	
	InitSpinner();	
	
	CheckAll();
	
	GetSettleInfo();
}

function InitSpinner()
{
	var spinners = $('.goods_count_input');
	
	for (var i=0; i<spinners.length; i++)
	{
		var _v = $(spinners[i]).val();
		var _max = $(spinners[i]).attr('_max');
		
		
		$(spinners[i]).spinner({
			value: parseInt(_v),
			min: 1,
			max: parseInt(_max),
			onChanged: function(_this, v, changeValue)
			{				
				GetSettleInfo();
				
				var id = $(_this).parents('.cart_item').children('input[type="checkbox"]').attr('id');
				var  _max2 = $(_this).attr('_max');
				
				AddToCart(id, changeValue, parseInt(_max2));		
				
				$("#circle_cart_count").html(GetCartCount());
			}
		});
	}	
}

function GetSettleInfo()
{
	var carts = $('.cart_item');
	
	var amount = 0;
	
	for (var i=0; i<carts.length; i++)
	{
		if ($(carts[i]).children('input[type="checkbox"]').is(':checked'))
		{
			var price = parseFloat($(carts[i]).find('.goods_price').children('strong').html());
			var count = parseFloat($(carts[i]).find('.goods_count_input').val());
			
			amount += price * count;
		}
	}
	
	$('#pay_amount').find('strong').html(amount.toFixed(2));
}

function DeleteFromCart(obj, id)
{	
	RemoveCart(id);
	
	$(obj).parents('.line-wrapper').remove();
	
	GetSettleInfo();
	$("#circle_cart_count").html(GetCartCount());
}

function Settle()
{
	var carts = $('.cart_item');
	
	var cartInfo = [];
	
	var totalCount = 0;
	
	for (var i=0; i<carts.length; i++)
	{
		if ($(carts[i]).children('input[type="checkbox"]').is(':checked'))
		{
			var id = $(carts[i]).children('input[type="checkbox"]').attr('id');
			var name = $(carts[i]).find('.goods_name').html();
			var count = parseFloat($(carts[i]).find('.goods_count_input').val());
			var price = parseFloat($(carts[i]).find('.goods_price').children('strong').html());
			var imgUrl = $(carts[i]).find('img').attr('src');
			
			var cartItem = {};
			cartItem.commodityId = id;
			cartItem.commodityName = name;
			cartItem.commodityNums = count;
			cartItem.commodityAmount = price;
			cartItem.photo = imgUrl;
			
			cartInfo.push(cartItem);
			console.log(cartInfo);
			totalCount += count;
		}
	}
	
	/*if (totalCount <= 0)
	{
		ShowTip("请勾选你需要购买的商品", 110);
		
		return;
	}
	else if (totalCount <= 6)
	{
		var cartInfoBase64 = base64.encode(JSON.stringify(cartInfo));
		
		GotoPay(encodeURIComponent(cartInfoBase64));
	}
	else
	{
		ShowTip("当次最多购买【6】件商品，请调整后进行结算", 110);
		
		return;
	}*/
	if (totalCount <= 0)
	{
		ShowTip("请选购/勾选你需要购买的商品", 110);
		
		return;
	}
	else
	{	
		//var cartInfoBase64 = base64.encode(JSON.stringify(cartInfo));
		//console.log(cartInfoBase64);
		var cartInfoBase64 = JSON.stringify(cartInfo);
		GotoPay(encodeURIComponent(cartInfoBase64));		
		//GotoPay(cartInfo);
		//GotoUrl('/mobile/GotoPay?OrderInfo="+"+orderInfo+"');
		//GotoUrl('/WEB-INF/pages/mobile/main/food/pay.jsp');
		//window.location.href = "/mobile/GotoPay?OrderInfo="+cartInfo;
	}
}